# Copyright 2024 PKU-Alignment Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

import argparse
import json

from frechet_audio_distance import FrechetAudioDistance


def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--datasetpath',
        type=str,
        required=True,
        help='Path to the directory containing the original audio files.',
    )
    parser.add_argument(
        '--logs',
        type=str,
        required=True,
        help='Path to the directory containing the audio files generated by the model.',
    )
    parser.add_argument(
        '--name', type=str, required=True, help='Path where the FAD score should be saved.'
    )
    return parser.parse_args()


def get_fad_score(datasetpath, logs, output_dir):
    frechet = FrechetAudioDistance(
        model_name='vggish', sample_rate=16000, use_pca=False, use_activation=False, verbose=False
    )
    fad_score = frechet.score(
        background_dir=datasetpath.strip("'"), eval_dir=logs.strip("'"), dtype='float32'
    )

    fad_score = float(max(fad_score, 0))
    FADScore = {'fad_score': fad_score}

    with open(output_dir.strip("'"), 'w') as file:
        json.dump(FADScore, file, indent=4)


def main():
    args = parse_arguments()
    get_fad_score(args.datasetpath, args.logs, args.name)


if __name__ == '__main__':
    main()
